package com.iavstream.utility;

import android.app.Activity;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.database.Cursor;
import android.database.sqlite.SQLiteException;
import android.net.Uri;
import android.os.Bundle;
import android.telephony.SmsManager;
import android.telephony.SmsMessage;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

public class MsgStuff {	

	  Context mContext = null;
	
	  private String SEND_SMS_ACTION = "SENT_SMS_ACTION";
	  private String DELIVERY_SMS_ACTION = "DELIVERY_SMS_ACTION";
	  
	  public MsgStuff(Context c,boolean receive)
      {
    	  mContext=c;
    	  if(receive==true)
    	  {
    	      mContext.registerReceiver(SMSBroadcastReceiver, new IntentFilter(
    	        "android.provider.Telephony.SMS_RECEIVED")); 
    	  }
      }

	  public void SendMsg(String phoneNumber,String MsgStr)
	  {		 
		  SmsManager sms = SmsManager.getDefault();
		  Intent sendIntent = new Intent(SEND_SMS_ACTION);
		  PendingIntent sendPI = PendingIntent.getBroadcast(mContext, 0, sendIntent, 0);
		  Intent deliveryIntent = new Intent(DELIVERY_SMS_ACTION);
		  PendingIntent deliveryPI = PendingIntent.getBroadcast(mContext, 0, deliveryIntent, 0);
		  List<String> divideContents = sms.divideMessage(MsgStr);
		  for (String text : divideContents) {
			  sms.sendTextMessage(phoneNumber, null, text, sendPI, deliveryPI);
		  }
	  }
	/*  public ArrayList<String> getLatestRtspAddress() {
			
			//final String SMS_URI_ALL = "content://sms/";
			final String SMS_URI_INBOX = "content://sms/inbox";
		  //final String SMS_URI_SEND = "content://sms/sent";
		  //final String SMS_URI_DRAFT = "content://sms/draft";
			
			//StringBuilder smsBuilder = new StringBuilder();
		    ArrayList<String> mMsgInfo = new ArrayList<String>();

			try {
				
				ContentResolver cr = mContext.getContentResolver();
				String[] projection = new String[] { "_id", "address", "person",
						"body","type", "date", "type" };
				Uri uri = Uri.parse(SMS_URI_INBOX);
				Cursor cur = cr.query(uri, projection, null, null, "date desc");
				if (cur.moveToFirst()) {
					String name;
					String phoneNumber;
					String smsbody;
					String date;
					String type;
					String rtsp;

					int nameColumn = cur.getColumnIndex("person");
					int phoneNumberColumn = cur.getColumnIndex("address");
					int smsbodyColumn = cur.getColumnIndex("body");
					int dateColumn = cur.getColumnIndex("date");
					int typeColumn = cur.getColumnIndex("type");
					
					do {
						smsbody=cur.getString(smsbodyColumn);
						rtsp=SearchRtspAddress(smsbody);
						if(rtsp==null)
						{
							
						}
						else
						{
							mMsgInfo.add(cur.getString(nameColumn));// add name
							mMsgInfo.add(cur.getString(phoneNumberColumn));//add phonenumber
							mMsgInfo.add(rtsp);	//add rtsp address
							//add message date
							SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
					        Date d = new Date(Long.parseLong(cur.getString(dateColumn)));
					        date = dateFormat.format(d);
					        mMsgInfo.add(date);
					        //add message type
					        int typeId = cur.getInt(typeColumn);					        
					        if (typeId == 1) {
						        type = "����";
					        } else if (typeId == 2) {
						        type = "����";
					        } else {
						        type = "δ֪";
					        }
					        mMsgInfo.add(type);
							return mMsgInfo;
						}
					} while (cur.moveToNext());
				} else {
					return null;
				}
			} catch (SQLiteException ex) {
				//Log.d("SQLiteException in getLatestRtspAddress", ex.getMessage());
			}
			
			return null;//smsBuilder.toString();
		}*/

		public ArrayList<String> getAllRtspAddress() {
			
			//final String SMS_URI_ALL = "content://sms/"; 		//���ж���
			final String SMS_URI_INBOX = "content://sms/inbox";	//������
		//	final String SMS_URI_SEND = "content://sms/sent";	//������
		//	final String SMS_URI_DRAFT = "content://sms/draft";	//�ݸ���
			
			//StringBuilder smsBuilder = new StringBuilder();
			 ArrayList<String> mMsgInfo = new ArrayList<String>();
			
			try {
				
				ContentResolver cr = mContext.getContentResolver();
				String[] projection = new String[] { "_id", "address", "person",
						"body","type", "date", "type" };
				Uri uri = Uri.parse(SMS_URI_INBOX);
				Cursor cur = cr.query(uri, projection, null, null, "date desc");
				if (cur.moveToFirst()) {
					String name;
					String phoneNumber;
					String smsbody;
					String date;
					String type;
					String rtsp;
					int nameColumn = cur.getColumnIndex("person");
					int phoneNumberColumn = cur.getColumnIndex("address");
					int smsbodyColumn = cur.getColumnIndex("body");
					int dateColumn = cur.getColumnIndex("date");
					int typeColumn = cur.getColumnIndex("type");
					
					do {
						  smsbody=cur.getString(smsbodyColumn);
						  rtsp=SearchRtspAddress(smsbody);
						  if(rtsp==null)
						 {
							
						  }
						  else
						 {
							mMsgInfo.add(cur.getString(nameColumn));//1 add name
							mMsgInfo.add(cur.getString(phoneNumberColumn));//2 add phonenumber
							mMsgInfo.add(rtsp);	//3 add rtsp address
							//4 add message date
							SimpleDateFormat dateFormat = new SimpleDateFormat(
							"yyyy-MM-dd hh:mm:ss");							
					        Date d = new Date(Long.parseLong(cur.getString(dateColumn)));
					        date = dateFormat.format(d);
					        mMsgInfo.add(date);
						 }
					} while (cur.moveToNext());

					return mMsgInfo;
				} else {
					return null;
				}
			} catch (SQLiteException ex) {
				//Log.d("SQLiteException in getLatestRtspAddress", ex.getMessage());
			}
			
			return null;//smsBuilder.toString();
		}

		public String SearchRtspAddress(String content) {
			String str = null;
			String rtsp = new String("rtsp://");
			String sdp = new String(".sdp");
			int rtspindex,sdpindex;
			//serch the "rtsp://" and ".sdp" location
			rtspindex=content.indexOf(rtsp);
			sdpindex=content.indexOf(sdp);
			if(rtspindex==-1||sdpindex==-1)return str;
			//get the sub string
			str=content.substring(rtspindex, sdpindex+4);
			return str;
		}
	
	  BroadcastReceiver sendMessage = new BroadcastReceiver() {
		    @Override
		    public void onReceive(Context context, Intent intent) {
		      switch (getResultCode()) {
		        case Activity.RESULT_OK:
		        //  Toast.makeText(context, "���ŷ��ͳɹ���", Toast.LENGTH_SHORT).show();
		        //  endTime.setText("���ͽ���ʱ�䣺" + calendar.getTime().toString());
		       //   resultText.setText("���ŷ��ͳɹ���");
		          break;

		        default:
		        //  Toast.makeText(context, "���ŷ���ʧ�ܣ�", Toast.LENGTH_SHORT).show();
		       //   resultText.setText("���ŷ���ʧ�ܣ�");
		          break;
		      }
		    }
		  };

	 BroadcastReceiver receiveMessage = new BroadcastReceiver() {

		    @Override
		    public void onReceive(Context context, Intent intent) {
		    //  Toast.makeText(context, "�Է����ճɹ���", Toast.LENGTH_SHORT).show();
		    }
		  };

    BroadcastReceiver SMSBroadcastReceiver = new BroadcastReceiver() {
		    @Override
		    public void onReceive(Context context, Intent intent) {

		    	//Toast.makeText(context, "�յ�����", Toast.LENGTH_LONG).show();
		        SmsMessage msg = null;
		        Bundle bundle = intent.getExtras();
		        if (bundle != null) {
		        Object[] pdusObj = (Object[]) bundle.get("pdus");
		        for (Object p : pdusObj) {
		          msg = SmsMessage.createFromPdu((byte[]) p);
		          String msgTxt = msg.getMessageBody();
		          Date date = new Date(msg.getTimestampMillis());
		        //  msg.get
		          
		          SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		          String receiveTime = format.format(date);
		          String senderNumber = msg.getOriginatingAddress();
		         // Toast.makeText(context, "�յ����ţ����룺"+senderNumber+"���ݣ�"+msgTxt, Toast.LENGTH_LONG).show();
		        }
		       // return;
		      }
		    }
          };	
	
}